package com.example.jpetstoreclient.controller;

import com.example.jpetstoreclient.common.CommonResponse;
import com.example.jpetstoreclient.service.EmailService;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@Validated
@RestController
@RequestMapping("/email")
public class EmailController {
    private static final int CODE_LENGTH = 5;
    @Autowired
    private EmailService emailService;
    private String code;

    @GetMapping("/send/{email}")
    public CommonResponse<Object> send(@PathVariable @Email(message = "邮箱格式不合法") String email){
        Random random = new Random(System.currentTimeMillis());
        code = String.format("%0" + CODE_LENGTH + "d", random.nextLong(quickPow(10, CODE_LENGTH)));
        emailService.sendVerifyCode(email, code);
        return CommonResponse.createForSuccessMessage("发送成功");
    }

    @GetMapping("/verify/{code}")
    public CommonResponse<Object> verify(@PathVariable @NotBlank(message = "验证码不能为空") String code){
        if (this.code.equals(code)){
            return CommonResponse.createForSuccessMessage("验证码正确");
        }
        return CommonResponse.createForError("验证码错误");
    }

    private long quickPow(long base, int exp){
        if (exp < 0) return -1;
        long res = 1;
        while(exp != 0){
            if ((exp & 1) == 1) res *= base;
            base *= base;
            exp >>= 1;
        }
        return res;
    }
}
